#!/bin/sh

SRCDIR="@top_srcdir@"
TEST_SRCDIR="${SRCDIR}/tests"
BUILDDIR="@top_builddir@"
TEST_BUILDDIR="${BUILDDIR}/tests"
PYTHON="@PYTHON_EXECUTABLE@"

PYTHON_SET=false
PRINT_MODE=false
while echo $1 | grep '^-' >/dev/null; do
    if [ "X$1" = "X--python" ]; then
	PYTHON_SET=true
    elif [ "X$1" = "X--print" ]; then
	PRINT_MODE=true
    elif [ "X$1" = "X--" ]; then
	break
    else
	echo "Unknown option: $1" 1>&2
	exit 1
    fi
    shift
done

if [ ! -e ca ]; then
    ${TEST_SRCDIR}/make_keys;
fi

if [ -z "$1" ]; then
    echo "No test given" 1>&2
    exit 1
fi

TEST=$1
shift

RUNPREFIX=""
if [ -e "${TEST_BUILDDIR}/${TEST}" ]; then
    TEST="${TEST_BUILDDIR}/${TEST}"
elif [ -e "${TEST_SRCDIR}/${TEST}" ]; then
    TEST="${TEST_SRCDIR}/${TEST}"
else
    echo "Test ${TEST} not found" 1>&2
    exit 1
fi

if ${PYTHON_SET}; then
    PYTHON_MODE=true
elif echo "${TEST}" | grep '\.py$' >/dev/null; then
    PYTHON_MODE=true
else
    PYTHON_MODE=false
fi

if ${PYTHON_MODE}; then
    export PYTHONPATH=${BUILDDIR}/swig/python:${BUILDDIR}/swig/python/.libs:${BUILDDIR}/glib/swig/python:${BUILDDIR}/glib/swig/python/.libs:${BUILDDIR}/tcl/swig/python:${BUILDDIR}/tcl/swig/python/.libs:${TEST_BUILDDIR}
    # We need to put the DLL in PATH for MSYS on Windows
    if [ ! -z "$MSYSTEM" ]; then
	export PATH=${BUILDDIR}/lib:${BUILDDIR}/lib/.libs:$PATH:${BUILDDIR}/swig/python/.libs:${BUILDDIR}/glib/.libs::${BUILDDIR}/tcl/.libs
    else
	export LD_LIBRARY_PATH=${BUILDDIR}/lib:${BUILDDIR}/lib/.libs:${BUILDDIR}/swig/python/.libs:${BUILDDIR}/glib/.libs::${BUILDDIR}/tcl/.libs
    fi
    TEST="${PYTHON} ${TEST}"
else
    if [ ! -x ${TEST} ]; then
	echo "Test ${TEST} is not executable" 1>&2
	exit 1
    fi
fi
	
if ${PRINT_MODE}; then
    echo export PYTHONPATH="${PYTHONPATH}"
    if [ ! -z "$MSYSTEM" ]; then
	echo export PATH=${BUILDDIR}/lib:${BUILDDIR}/lib/.libs:\$PATH:${BUILDDIR}/swig/python/.libs:${BUILDDIR}/glib/.libs:${BUILDDIR}/tcl/.libs
    else
	echo export LD_LIBRARY_PATH="${LD_LIBRARY_PATH}"
    fi
    echo ${RUNPREFIX} ${TEST} $*
else
    # Run the test with each available OS handler
    for i in default @TCL_DIR@ @GLIB_DIR@; do
	echo "Testing with '$i'"
	export GENSIO_TEST_OS_HANDLER=$i
	${RUNPREFIX} ${TEST} $*
    done
fi
